package com.sicaolong.eventdefine.model;

import com.sicaolong.eventdefine.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
public class EventDefManager implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware {

    public static EventDefManager instance = new EventDefManager();

    private EventDefManager() {
        log.info("初始化");
    }

    public static EventDefManager getInstance() {
        return instance;
    }

    private ApplicationContext applicationContext;
    private Map<String, EventDefine> events = new HashMap<>();

    public Map<String, EventDefine> getEvents() {
        return events;
    }

    public void setEvents(Map<String, EventDefine> events) {
        this.events = events;
    }

    public EventTemplate getEventTemplate(String eventType) {
        return Optional.ofNullable(events.get(eventType))
                .map(EventDefine::getEventTemplate)
                .orElse(null);
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, EventDefine> beansOfType = this.applicationContext.getBeansOfType(EventDefine.class);
        for (EventDefine bean : beansOfType.values()) {
            events.put(bean.getType(), bean);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
